package com.hzhk.happyrent.ui.activity.personal;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.CodeModel;
import com.hzhk.happyrent.bean.rent.BaseModel;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyStringResponse;
import com.hzhk.happyrent.network.MyStringTransResponse;
import com.hzhk.happyrent.ui.view.ClearEditText;
import com.hzhk.happyrent.utils.PatternStringUtirl;
import com.hzhk.happyrent.utils.StringUtils;
import com.hzhk.happyrent.utils.SystemUtils;
import com.tamic.novate.Throwable;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ForgetActivity extends AppCompatActivity {

    @BindView(R.id.activity_titlebar_left)
    ImageView activityTitlebarLeft;
    @BindView(R.id.activity_titlebar_center)
    TextView activityTitlebarCenter;
    @BindView(R.id.activity_titlebar_right)
    ImageView activityTitlebarRight;
    @BindView(R.id.reg_act_user_phone)
    ClearEditText regActUserPhone;
    @BindView(R.id.reg_act_user_pwd)
    ClearEditText regActUserPwd;
    @BindView(R.id.reg_vcode)
    ClearEditText regVcode;
    @BindView(R.id.btn_sendvcode)
    Button btnSendvcode;
    @BindView(R.id.btn_register)
    Button btnRegister;
    private TimeCount time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        activityTitlebarCenter.setText(getString(R.string.password_forget));
        activityTitlebarRight.setVisibility(View.GONE);
        activityTitlebarLeft.setImageResource(R.drawable.back);
        regActUserPhone.addTextChangedListener(new TextChange(1));
        regActUserPwd.addTextChangedListener(new TextChange(1));
        regVcode.addTextChangedListener(new TextChange(2));
        time = new TimeCount(59200,100);
    }

    @OnClick({R.id.activity_titlebar_left, R.id.btn_sendvcode, R.id.btn_register})
    public void onViewClicked(View view) {
        String phone = regActUserPhone.getText().toString().trim();
        String vcode = regVcode.getText().toString().trim();
        String pwd = regActUserPwd.getText().toString().trim();
        switch (view.getId()) {
            case R.id.activity_titlebar_left:
                finish();
                break;
            case R.id.btn_sendvcode:
                judgePhone(phone, pwd);
                break;
            case R.id.btn_register:
                judgePhone(phone, pwd, vcode);
                break;
        }
    }

    public void showToast(int id) {
        Toast.makeText(this, id, Toast.LENGTH_SHORT).show();
    }

    private void judgePhone(String phone, String pwd, String vcode) {
        if (StringUtils.isEmpty(phone)) {
            showToast(R.string.tv_phone_is_null);// 请输入手机号
        } else if (!PatternStringUtirl.isMobileNum(phone)) {
            showToast(R.string.tv_phone_isnot_right);// 输入手机号格式不正确
        } else if (StringUtils.isEmpty(pwd)) {
            showToast(R.string.tv_pwd_is_null);// 请输入密码
        } else if (!SystemUtils.isLetterDigit(pwd)) {
            showToast(R.string.tv_pwd_rule);// 请输入6位以上的密码
        } else if (StringUtils.isEmpty(vcode)) {
            showToast(R.string.tv_vcode_is_null);// 请输入验证码
        } else if (vcode.length() < 6) {
            showToast(R.string.tv_isnot_vcode);// 验证码格式不正确
        } else {
            register(phone, pwd, vcode);
        }
    }

    private void register(final String phone, final String pwd, String vcode) {
        Map<String, Object> params = new HashMap<>();
        params.put("phone", phone);
        params.put("code", vcode);
        params.put("password", pwd);
        HttpManager.getInstance().perform_post(API.FIND_PWD, params, new MyStringResponse(this) {
            @Override
            public void onNext(Object tag, String response) {
                CodeModel codeModel=new Gson().fromJson(response,CodeModel.class);
                if(codeModel.getErrCode()==0){
                    BaseModel baseModel = new Gson().fromJson(response, BaseModel.class);
                    time.cancel();
                    Toast.makeText(ForgetActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
                    finish();
                }else {
                    Toast.makeText(ForgetActivity.this, codeModel.getMessage() + "", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {
//                Toast.makeText(ForgetActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

        });
    }

    private void judgePhone(String phone, String pwd) {
        if (StringUtils.isEmpty(phone)) {
            showToast(R.string.tv_phone_is_null);// "请输入手机号"
        } else {
            if (phone.length() < 11) {
                showToast(R.string.tv_phone_isnot_right);// "输入手机号格式不正确"
            } else if (!PatternStringUtirl.isMobileNum(phone)) {
                showToast(R.string.tv_phone_isnot_right);
            } else if (StringUtils.isEmpty(pwd)) {
                showToast(R.string.tv_pwd_is_null);
            } else if (pwd.length() < 6) {
                showToast(R.string.tv_pwd_rule);
            } else if (!SystemUtils.isLetterDigit(pwd)) {
                showToast(R.string.tv_pwd_rule_num_and_letter);
            } else {
                getVCode(phone);
            }
        }
    }

    private void getVCode(String phone) {
        Map<String, Object> params = new HashMap<>();
        params.put("phone", phone);
        HttpManager.getInstance().perform_post(API.SMS_SEND, params, new MyStringResponse(this) {
            @Override
            public void onNext(Object tag, String response) {
                BaseModel baseModel = new Gson().fromJson(response, BaseModel.class);
                if (0==baseModel.getErrCode()) {
                    Toast.makeText(ForgetActivity.this, R.string.apply_success, Toast.LENGTH_SHORT).show();
                    time.start();
                } else {
                    Toast.makeText(ForgetActivity.this, baseModel.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {
//                Toast.makeText(ForgetActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }
        });
    }

    // EditText监听器
    class TextChange implements TextWatcher {
        private int flags = 0;

        public TextChange(int flags) {
            this.flags = flags;
        }

        @Override
        public void afterTextChanged(Editable arg0) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence cs, int start, int before,
                                  int count) {
            boolean Sign1 = regActUserPhone.getText().length() > 10;
            boolean Sign2 = regActUserPwd.getText().length() > 5;
            boolean Sign3 = regVcode.getText().length() > 3;
            if (flags == 1) {

                if (Sign1 & Sign2) {
                    btnSendvcode
                            .setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_w));
                    btnSendvcode.setTextColor(getResources().getColor(R.color.black_60));
                    btnSendvcode.setEnabled(true);
                } else {
                    // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
                    btnSendvcode
                            .setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_g));
                    btnSendvcode.setTextColor(getResources().getColor(R.color.white_90));
                    btnSendvcode.setEnabled(false);
                }

            }
            if (Sign1 & Sign2 & Sign3) {
                btnRegister.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_red_selector));
                btnRegister.setEnabled(true);
            } else {
                // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
                btnRegister.setEnabled(false);
            }

        }
    }
    // 验证码倒计时
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            btnSendvcode.setText(R.string.get_again);
            btnSendvcode.setEnabled(true);
            btnSendvcode.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_w));
            btnSendvcode.setTextColor(getResources().getColor(R.color.black_60));
            boolean Sign1 = regActUserPhone.getText().length() > 10;
            boolean Sign2 = regActUserPwd.getText().length() > 5;
            boolean Sign3 = regVcode.getText().length() > 3;
            if (Sign1 & Sign2) {
                btnSendvcode
                        .setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_w));
                btnSendvcode.setTextColor(getResources().getColor(R.color.black_60));
                btnSendvcode.setEnabled(true);
            } else {
                // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
                btnSendvcode
                        .setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_g));
                btnSendvcode.setTextColor(getResources().getColor(R.color.white_90));
                btnSendvcode.setEnabled(false);
            }
            if (Sign1 & Sign2 & Sign3) {
                btnRegister.setBackgroundResource(R.drawable.btn_red_selector);
                btnRegister.setEnabled(true);
            } else {
                // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
                btnRegister.setBackgroundResource(R.drawable.bg_btn_gray_solid);
                btnRegister.setEnabled(false);
            }

        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            btnSendvcode.setBackgroundResource(R.drawable.img_time_tick_g);
            btnSendvcode.setTextColor(getResources().getColor(R.color.white_90));
            btnSendvcode.setEnabled(false);
            btnSendvcode.setText((millisUntilFinished + 800) / 1000 + "s");
        }
    }
}
